import Foundation

enum OsnEvent:String {
    case GroupInfoUpdated = "GroupInfoUpdated"
    case GroupMemberUpdated = "GroupMemberUpdated"
    case GroupAddAdmin = "GroupAddAdmin"
    case GroupDelAdmin = "GroupDelAdmin"
    case GroupMute = "GroupMute"
    case GroupAllow = "GroupAllow"
    case UserInfoUpdated = "UserInfoUpdated"
    case FriendInfoUpdated = "FriendInfoUpdated"
    case FriendListUpdated = "FriendListUpdated"
    case FriendRequestUpdated = "FriendRequestUpdated"
    case ConnectionStatusChanged = "ConnectionStatusChanged"
    case ReceiveMessages = "ReceiveMessages"
    case RecallMessages = "RecallMessages"
    case DeleteMessages = "DeleteMessages"
    case TokenExpire = "TokenExpire"
    case KickOffAction = "KickOffAction"
    case kTokenError = "kTokenError"
    case NewDapp = "NewDapp"
    case kUpDateConversation = "kUpDateConversation"
}
class EventService {
    private var observers: [OsnEvent: [(id: String, callback: (_ data:Any) -> Void)]] = [:]

    // 注册回调
    func addObserver(_ event: OsnEvent, _ callback: @escaping (_ data:Any) -> Void) -> String {
        let id = UUID().uuidString
        if observers[event] == nil {
            observers[event] = [(id: id, callback: callback)]
        } else {
            observers[event]?.append((id: id, callback: callback))
        }
        return id
    }
    func addObserver(_ event: OsnEvent, _ name: String, _ callback: @escaping (_ data:Any) -> Void) {
        if observers[event] == nil {
            observers[event] = [(id: name, callback: callback)]
        } else {
            observers[event]?.append((id: name, callback: callback))
        }
    }

    // 移除回调
    func removeObserver(_ event: OsnEvent, _ id: String) {
        if let callbacks = observers[event] {
            observers[event] = callbacks.filter { $0.id != id }
        }
    }

    // 发布消息
    func post(_ event: OsnEvent, _ data:Any) {
        if let callbacks = observers[event] {
            for (_, callback) in callbacks {
                callback(data)
            }
        }
    }
    func clear(){
        observers.removeAll()
    }
    
    func postNotifcation () {
        let content = UNMutableNotificationContent()
        content.title = ""
        content.subtitle = ""
        content.body = "你有一条新的消息，请查看"
        content.sound = UNNotificationSound.default

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
        let request = UNNotificationRequest(identifier: "com.Engineering.Nanochem", content: content, trigger: trigger)
          
        UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
            if let error = error {
                print("Failed to add notification request with error: \(error)")
            }
        })
        DispatchQueue.main.async {
            UIApplication.shared.applicationIconBadgeNumber = 1
        }
    }
}
let geventService = EventService()
